package com.guijianpan.system.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.guijianpan.framework.constant.Constant;
import com.guijianpan.framework.controller.BaseController;
import com.guijianpan.system.domain.User;
import com.guijianpan.system.service.MenuService;
import com.guijianpan.system.service.UserService;

@Controller
public class UserController extends BaseController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private MenuService menuService;
	
	@RequestMapping(value="/login", method=RequestMethod.GET)
	public ModelAndView login() {
		return new ModelAndView("login/login");
	}
	
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public ModelAndView login(HttpServletRequest request, String name, String pwd) {
		User user = userService.findByNameAndPwd(name, pwd);
		if(null == user) {
			return new ModelAndView("login/login").addObject("msg", "用户名或密码错误");
		} else {	// 登录成功
			user.initUserRights(menuService.findFirstLevelMenu());
			request.getSession().setAttribute(Constant.SESSION_KEY_LOGIN_USER, user);
		}
		return new ModelAndView("redirect:/home");
	}
	
	@RequestMapping(value="/loginout", method=RequestMethod.GET)
	public ModelAndView loginout(HttpServletRequest request) {
		request.getSession().removeAttribute(Constant.SESSION_KEY_LOGIN_USER);
		return new ModelAndView("redirect:/login");
	}
	
}
